package com.easy.api.factory.api.request;

import com.easy.api.annotation.ApiMapping;
import com.easy.api.annotation.ApiProxy;
import com.easy.api.bean.api.OpenConfig;
import com.easy.api.type.RequestFormat;
import com.easy.api.utils.ApiUtils;
import com.easy.api.utils.ApplicationContextUtils;
import com.easy.api.utils.ObjectUtils;
import org.springframework.context.ApplicationContext;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @Author liuyuan
 * @Date 2020-04-24 17:07
 * @Version 1.0
 */
public abstract class HeaderRequest{

    public String requestUrl;

    public Method method;

    public String host;

    public RequestFormat requestFormat;

    public  OpenConfig config;

    public String action;

    public Class<?> requestClass;

    public boolean isRequestClass;

    public abstract Object requestStrategy(Object param) throws IOException;

    public void buildHeaderRequest(ApiProxy apiProxy, ApiMapping apiMapping, OpenConfig config, Method method){
        this.config = config;
        this.requestUrl = ApiUtils.getRequestUrl(apiProxy, apiMapping);
        this.method = method;
        this.host = apiProxy.host();
        this.requestClass = apiProxy.requestClass();
        //this.httpMethod = apiMapping.method();
        this.action = apiMapping.value();
        this.requestFormat = apiMapping.format();
        this.isRequestClass = apiMapping.isRequestClass();
    }

    public Map<String, String> buildRequestParam(Object param) {
        Map<String, String> requestParam;
        if(!Void.class.getTypeName().equals(requestClass) && this.isRequestClass){
            /**
             * 构建请求参数策略
             * */
            ApplicationContext applicationContext = ApplicationContextUtils.getApplicationContext();
            RequestBuildParam requestBuildParam = (RequestBuildParam)applicationContext.getBean(requestClass);
            requestParam = requestBuildParam.buildParam(param, config);
        }else {
            requestParam = ObjectUtils.toMapStr(param);
        }
        return requestParam;
    }
}
